using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using PackTracker.Business;

public partial class Veiculos : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected override void OnPreRenderComplete(EventArgs e)
    {
        base.OnPreRenderComplete(e);
        ApplyAuthorizationRules();
    }

    private void ApplyAuthorizationRules()
    {
        novoItem.Visible = Veiculo.CanAddObject();
        veiculoGrid.Visible = Veiculo.CanGetObject();
        veiculoGrid.Columns[veiculoGrid.Columns.Count - 1].Visible = Veiculo.CanEditObject();
    }


    #region GridView Veiculo
    protected void veiculoListDataSource_SelectObject(object sender, Csla.Web.SelectObjectArgs e)
    {
        e.BusinessObject = getVeiculos();//VeiculoCollection.GetVeiculoCollection();
    }

    protected void veiculoGrid_CancelEdit(object sender, GridViewCancelEditEventArgs e)
    {
        //Limpa o ViewState
        ViewState.Remove("veiculos");
        veiculoGrid.DataBind();
    }

    protected void veiculoGrid_RowUpdated(object sender, GridViewUpdatedEventArgs e)
    {
        VeiculoCollection veiculos = VeiculoCollection.GetVeiculoCollection();
        int veiculoId = int.Parse(e.Keys["Id"].ToString());
        Veiculo veiculo = null;

        if (veiculoId == 0)
            veiculo = Veiculo.NewVeiculo();
        else
            veiculo = Veiculo.GetVeiculo(veiculoId);

        Csla.Data.DataMapper.Map(e.NewValues, veiculo);

        veiculo = veiculo.Save();
        veiculos.Add(veiculo);

        //Atualiza o ViewState
        veiculos = VeiculoCollection.GetVeiculoCollection();
        ViewState.Add("veiculos", veiculos);

        veiculoGrid.EditIndex = -1;
        veiculoGrid.DataBind();
    }
    #endregion

    protected void novoItem_Click(object sender, EventArgs e)
    {
        VeiculoCollection veiculos = getVeiculos();
        Veiculo veiculo = Veiculo.NewVeiculo();
        veiculos.Add(veiculo);

        //Atualiza o ViewState
        ViewState.Add("veiculos", veiculos);

        veiculoGrid.DataBind();
        veiculoGrid.EditIndex = veiculoGrid.Rows.Count - 1;
    }

    protected VeiculoCollection getVeiculos()
    {
        VeiculoCollection veiculos = ViewState["veiculos"] as VeiculoCollection;

        if (veiculos == null)
        {
            veiculos = VeiculoCollection.GetVeiculoCollection();
            ViewState.Add("veiculos", veiculos);
        }

        return veiculos;
    }

    protected void funcionarioListDataSource_SelectObject(object sender, Csla.Web.SelectObjectArgs e)
    {
        e.BusinessObject = FuncionarioCollection.GetFuncionarioCollection();
    }
}
